package com.rc.saas.tenant.service.market;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.common.utils.DateUtil;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.mapper.market.MarketActivityMapper;
import com.rc.saas.tenant.mapper.market.MarketActivityRecordMapper;
import com.rc.saas.tenant.mapper.market.MarketActivityTicketMapper;
import com.rc.saas.tenant.model.market.*;
import com.rc.saas.tenant.search.activity.ActivityMemberSearch;
import com.rc.saas.tenant.search.market.MarketSearch;
import com.rc.saas.tenant.vo.market.ActivityEchartsResult;
import com.rc.saas.tenant.vo.market.MarketActivityDiscountVo;
import com.rc.saas.tenant.vo.market.MarketActivityRecordVo;
import com.rc.saas.tenant.vo.market.MarketActivityVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author frog
 * @date 2021/9/16
 */
@Service
public class MarketActivityServiceImpl implements MarketActivityService {

    @Autowired
    private MarketActivityMapper marketActivityMapper;

    @Autowired
    private MarketActivityTicketMapper marketActivityTicketMapper;

    @Autowired
    private MarketActivityRecordMapper marketActivityRecordMapper;

    @Autowired
    private MarketActivityRecordService marketActivityRecordService;

    @Override
    public MarketActivityMapper getMapper() {
        return marketActivityMapper;
    }

    @Override
    public MarketActivityVo selectMarketActivityByTenantCode(String tenantCode) {
        return marketActivityMapper.selectMarketActivityByTenantCode(tenantCode);
    }

    @Override
    public PageInfo<MarketActivity> listPageRechargeDiscount(BaseSearch baseSearch, String startTime, String endTime) throws ParseException {
        PageHelper.startPage(baseSearch.getOffset(), baseSearch.getLimit());
        MarketActivityExample marketActivityExample = new MarketActivityExample();
        MarketActivityExample.Criteria criteria = marketActivityExample.createCriteria();
        criteria.andTenantCodeEqualTo(baseSearch.getTenantCode()).andActivityTypeEqualTo("1");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtil.isNotBlank(startTime)) {
            criteria.andBeginTimeGreaterThanOrEqualTo(format.parse(startTime));
        }
        if (StringUtil.isNotBlank(endTime)) {
            criteria.andEndTimeLessThanOrEqualTo(format.parse(endTime));
        }
        marketActivityExample.setOrderByClause("created_time DESC");
        List<MarketActivity> marketActivities = marketActivityMapper.selectByExample(marketActivityExample);
        return new PageInfo<MarketActivity>(marketActivities);
    }

    @Override
    public Boolean isExecuteDiscount(Long marketActivityId, String tenantCode, Integer aliPay, Integer wxPay, Integer unPay, Integer abcPay,Integer isApp,Integer isWx) {
        //MarketActivityExample example = new MarketActivityExample();
        //example.createCriteria().andTenantCodeEqualTo(tenantCode).andStatusEqualTo("1").andActivityTypeEqualTo("1");
        List<MarketActivity> marketActivities = marketActivityMapper.listExecuteDiscount(tenantCode, aliPay, wxPay, unPay, abcPay,isApp,isWx);
        if (!CollectionUtils.isEmpty(marketActivities)) {
            Date date = new Date();
            long time = date.getTime();
            for (MarketActivity marketActivity : marketActivities) {
                if (marketActivityId == null || !marketActivityId.equals(marketActivity.getMarketActivityId())) {
                    if (marketActivity.getBeginTime().getTime() > time) {
                        return Boolean.TRUE;
                    } else if (marketActivity.getBeginTime().getTime() < time && marketActivity.getEndTime().getTime() > time) {
                        return Boolean.TRUE;
                    }
                }
            }
            return Boolean.FALSE;
        } else {
            return Boolean.FALSE;
        }
    }

    @Override
    public MarketActivityDiscountVo selectDiscountAndTicket(Long marketActivityId) {
        return marketActivityMapper.selectDiscountAndTicket(marketActivityId);
    }

    @Override
    public void insertDiscount(MarketActivity marketActivity, List<MarketActivityTicket> marketActivityTicketList) {
        marketActivityMapper.insertSelectiveReturnId(marketActivity);
        for (MarketActivityTicket marketActivityTicket : marketActivityTicketList) {
            marketActivityTicket.setMarketActivityId(marketActivity.getMarketActivityId());
            marketActivityTicketMapper.insertSelective(marketActivityTicket);
        }
    }

    @Override
    public void updateDiscount(MarketActivity marketActivity, List<MarketActivityTicket> marketActivityTicketList) {

        if (marketActivity.getAbcPay() == null) {
            marketActivity.setAbcPay(0);
        }
        if (marketActivity.getUnPay() == null) {
            marketActivity.setUnPay(0);
        }
        if (marketActivity.getWxPay() == null) {
            marketActivity.setWxPay(0);
        }
        if (marketActivity.getAliPay() == null) {
            marketActivity.setAliPay(0);
        }
        if (marketActivity.getIsApp() == null) {
            marketActivity.setIsApp(0);
        }
        if (marketActivity.getIsWx() == null) {
            marketActivity.setIsWx(0);
        }

        MarketActivityTicketExample marketActivityTicketExample = new MarketActivityTicketExample();
        marketActivityTicketExample.createCriteria().andMarketActivityIdEqualTo(marketActivity.getMarketActivityId());
        List<MarketActivityTicket> marketActivityTickets = marketActivityTicketMapper.selectByExample(marketActivityTicketExample);

        LinkedList<Long> activityTicketIds = new LinkedList<>();

        if (!CollectionUtils.isEmpty(marketActivityTickets)) {
            for (MarketActivityTicket marketActivityTicket : marketActivityTickets) {
                activityTicketIds.add(marketActivityTicket.getActivityTicketId());
            }

            MarketActivityTicketExample deleteBatchExample = new MarketActivityTicketExample();
            deleteBatchExample.createCriteria().andActivityTicketIdIn(activityTicketIds);
            marketActivityTicketMapper.deleteByExample(deleteBatchExample);

        }

        marketActivityMapper.updateByPrimaryKeySelective(marketActivity);

        for (MarketActivityTicket marketActivityTicket : marketActivityTicketList) {
            marketActivityTicket.setMarketActivityId(marketActivity.getMarketActivityId());
            marketActivityTicketMapper.insertSelective(marketActivityTicket);
        }
    }

    @Override
    public PageInfo<MarketActivityRecordVo> listPageMarketActivityRecord(BaseSearch baseSearch, String beginTime, String endTime) {
        PageHelper.startPage(baseSearch.getOffset(), baseSearch.getLimit());
        List<MarketActivityRecordVo> marketActivities = marketActivityRecordMapper.listPageMarketActivityRecord(baseSearch.getTenantCode(), beginTime, endTime);
        return new PageInfo<MarketActivityRecordVo>(marketActivities);
    }

    @Override
    public void insertMarketActivity(MarketActivity marketActivity) {

        marketActivity.setStatus("2");
        marketActivity.setMaxDiscountCount(1);
        marketActivity.setIsWx(1);
        marketActivity.setIsApp(1);
        marketActivityMapper.insertSelectiveReturnId(marketActivity);

        MarketActivityTicket marketActivityTicket=new MarketActivityTicket();

        marketActivityTicket.setTenantCode(marketActivity.getTenantCode());
        marketActivityTicket.setMarketActivityId(marketActivity.getMarketActivityId());
        marketActivityTicket.setActivityTicketId(marketActivity.getTicketTypeId());
        marketActivityTicket.setCreatedBy(marketActivity.getCreatedBy());
        marketActivityTicket.setCreatedTime(new Date());

        marketActivityTicketMapper.insertSelective(marketActivityTicket);

        MarketActivityRecord marketActivityRecord = new MarketActivityRecord();

        marketActivityRecord.setMarketActivityId(marketActivity.getMarketActivityId());
        marketActivityRecord.setTenantCode(marketActivity.getTenantCode());
        marketActivityRecord.setActivityName(marketActivity.getActivityName());
        marketActivityRecord.setTicketTypeId(marketActivity.getTicketTypeId());
        marketActivityRecord.setSendCount(marketActivity.getSendCount());
        marketActivityRecord.setSendType(marketActivity.getSendType());
        marketActivityRecord.setRewardType(marketActivity.getRewardType());
        marketActivityRecord.setRemark(marketActivity.getRemark());

        marketActivityRecordMapper.insertSelective(marketActivityRecord);

    }

    @Override
    public void updateMarketActivity(MarketActivity marketActivity) {
        if ("1".equals(marketActivity.getStatus())) {
            Date date = new Date();
            //找到最后一条记录
            MarketActivityRecord marketActivityRecord = marketActivityRecordMapper.selectLastOneRecord(marketActivity.getTenantCode());

            if (marketActivityRecord != null) {
                marketActivityRecord.setEndTime(date);
                marketActivityRecordMapper.updateByPrimaryKeySelective(marketActivityRecord);
            }

            MarketActivity oldMarketActivity = marketActivityMapper.selectByPrimaryKey(marketActivityRecord.getMarketActivityId());
            oldMarketActivity.setStatus("0");
            marketActivityMapper.updateByPrimaryKeySelective(oldMarketActivity);

            MarketActivityTicketExample example=new MarketActivityTicketExample();
            example.createCriteria().andMarketActivityIdEqualTo(oldMarketActivity.getMarketActivityId());
            List<MarketActivityTicket> marketActivityTickets=marketActivityTicketMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(marketActivityTickets)){
                for (MarketActivityTicket marketActivityTicket:marketActivityTickets){
                    marketActivityTicketMapper.deleteByPrimaryKey(marketActivityTicket.getActivityTicketId());
                }
            }

            marketActivity.setMarketActivityId(null);
            marketActivity.setMaxDiscountCount(1);
            marketActivity.setIsApp(1);
            marketActivity.setIsWx(1);
            marketActivityMapper.insertSelectiveReturnId(marketActivity);

            MarketActivityTicket marketActivityTicket=new MarketActivityTicket();
            marketActivityTicket.setTenantCode(marketActivity.getTenantCode());
            marketActivityTicket.setMarketActivityId(marketActivity.getMarketActivityId());
            marketActivityTicket.setTicketTypeId(marketActivity.getTicketTypeId());
            marketActivityTicket.setCreatedBy(marketActivityTicket.getCreatedBy());
            marketActivityTicket.setCreatedTime(new Date());
            marketActivityTicketMapper.insertSelective(marketActivityTicket);

            MarketActivityRecord newMarketActivityRecord = new MarketActivityRecord();
            newMarketActivityRecord.setTenantCode(marketActivity.getTenantCode());
            newMarketActivityRecord.setActivityName(marketActivity.getActivityName());
            newMarketActivityRecord.setTicketTypeId(marketActivity.getTicketTypeId());
            newMarketActivityRecord.setSendCount(marketActivity.getSendCount());
            newMarketActivityRecord.setSendType(marketActivity.getSendType());
            newMarketActivityRecord.setRewardType(marketActivity.getRewardType());
            newMarketActivityRecord.setRemark(marketActivity.getRemark());
            newMarketActivityRecord.setBeginTime(date);
            newMarketActivityRecord.setMarketActivityId(marketActivity.getMarketActivityId());

            marketActivityRecordMapper.insertSelective(newMarketActivityRecord);

        } else {
            marketActivityMapper.updateByPrimaryKeySelective(marketActivity);
        }

    }

    @Override
    public void updateMarketActivityStatus(MarketActivity marketActivity) {
        Date date = new Date();
        if ("2".equals(marketActivity.getStatus())) {
            marketActivity.setStatus("1");
            marketActivityMapper.updateByPrimaryKeySelective(marketActivity);

            MarketActivityRecord marketActivityRecord = marketActivityRecordMapper.selectLastOneRecord(marketActivity.getTenantCode());
            marketActivityRecord.setBeginTime(date);

            marketActivityRecordMapper.updateByPrimaryKeySelective(marketActivityRecord);
        } else if ("1".equals(marketActivity.getStatus())) {
            marketActivity.setStatus("0");
            marketActivityMapper.updateByPrimaryKeySelective(marketActivity);

            MarketActivityRecord marketActivityRecord = marketActivityRecordMapper.selectLastOneRecord(marketActivity.getTenantCode());
            marketActivityRecord.setEndTime(date);

            marketActivityRecordMapper.updateByPrimaryKeySelective(marketActivityRecord);
        }
    }

    @Override
    public PageInfo<MarketActivity> listPageMarketActivity(MarketSearch marketSearch) {
        PageHelper.startPage(marketSearch.getOffset(), marketSearch.getLimit());
        List<MarketActivity> marketActivities = marketActivityMapper.listPageMarketActivity(marketSearch);
        return new PageInfo<MarketActivity>(marketActivities);
    }

    @Override
    public PageInfo<MarketActivityMemberInfo> listPageActivityMemberInfo(ActivityMemberSearch activityMemberSearch) {
        PageHelper.startPage(activityMemberSearch.getOffset(), activityMemberSearch.getLimit());
        List<MarketActivityMemberInfo> marketActivities = marketActivityMapper.listPageActivityMemberInfo(activityMemberSearch);
        return new PageInfo<MarketActivityMemberInfo>(marketActivities);
    }

    @Override
    public JSONObject getMarKetStatistics(String isDayMonth) {
        JSONObject json = new JSONObject();
        //dateStr 获取前7天的日期
        List<String> dateStr = new ArrayList<>();
        int days = 0;
        String startTime = "";
        String endTime = "";
        List<ActivityEchartsResult> echartsDatas = null;
        if (StringUtils.equals("1",isDayMonth)){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String transformDate = simpleDateFormat.format(new Date());
            startTime = transformDate+" 00:00:00";//开始日期
            endTime = transformDate+" 23:59:59";//结束日期
            for (int i = 0; i < 24  ; i++) {
                dateStr.add(i+"");
            }
            json.put("dateStr",dateStr);
            echartsDatas = marketActivityMapper.getActivityEchartsDataDay(startTime,endTime);
        }else{
            //周 往前推7天
            days = 7;
            for (int i=7;i>=1;i--){
                dateStr.add(DateUtil.getPastDate(i,new Date()));
            }
            startTime = dateStr.get(0)+" 00:00:00";//开始日期
            endTime = dateStr.get(days-1)+" 23:59:59";//结束日期
            json.put("dateStr",dateStr);
            echartsDatas = marketActivityMapper.getActivityEchartsData(startTime,endTime);
        }
        List<Integer> czLst = new ArrayList<>();
        List<Integer> mjLst = new ArrayList<>();
        List<Integer> mfLst = new ArrayList<>();
        List<Integer> lxLst = new ArrayList<>();
        for (int i = 0; i <dateStr.size() ; i++) {
            Integer czNum = 0;
            Integer mjNum = 0;
            Integer mfNum = 0;
            Integer lxNum = 0;
            for (int j = 0; j <echartsDatas.size() ; j++) {
                if (StringUtils.equals(dateStr.get(i),echartsDatas.get(j).getDateStr())){
                    czNum = echartsDatas.get(j).getCzTotal();
                    mjNum = echartsDatas.get(j).getMjTotal();
                    mfNum = echartsDatas.get(j).getMfTotal();
                    lxNum = echartsDatas.get(j).getLxTotal();
                }
            }
            czLst.add(czNum);
            mjLst.add(mjNum);
            mfLst.add(mfNum);
            lxLst.add(lxNum);
        }
        json.put("czLst",czLst);
        json.put("mjLst",mjLst);
        json.put("mfLst",mfLst);
        json.put("lxLst",lxLst);
        return json;
    }

    @Override
    @Transactional
    public int saveMarketActivity(MarketActivity marketActivity) {
        int code = 0;
        marketActivityMapper.insertSelectiveReturnId(marketActivity);
        if (marketActivity.getMarketActivityId()<0){
            return code;
        }
        code = marketActivityRecordService.saveActivityChild(marketActivity);
        return code;
    }

    @Override
    public MarketActivity findById(Long id) {
        return marketActivityMapper.findById(id);
    }
}
